<?php



class QuestionAction extends ApiAction {
    public function top() {

        //Log::record('测试日志信息，这是警告级别','DEBUG');
        $top = I('get.tops');
        import('ORG.Util.Page');// 导入分页类
        $map = array();
        $QuestionDb = D('Question');

        $count = $QuestionDb->count();

        $Page = new Page($count);
        // 进行分页数据查询 注意page方法的参数的前面部分是当前的页数使用 $_GET[p]获取
        $nowPage = isset($_GET['p'])?$_GET['p']:1;
        $show       = $Page->show();// 分页显示输出
        $list = $QuestionDb->where($map)->order('sort ,date desc')->page($nowPage . ',' . $top)->select();
        $ret['result'] = 'ok';
        $ret['total'] = $QuestionDb->count();
        $ret['question'] = $list;
        //Log::record('--------------=======retret=========='.json_encode($ret),'DEBUG');
        echo json_encode($ret);
    }

    public function getQuestionById() {

        //Log::record('测试日志信息，这是警告级别','DEBUG');
        $qid = I('get.qid');
        $map = array();
        $map['qId']=$qid;
        $QuestionDb = D('Question');

        $question = $QuestionDb->where($map)->find();

        $WxUserDb = D('Wxuser');
        $headImg = $WxUserDb->join(' tp_member on tp_member.member_id=tp_wxuser.member_id')->field('headimgurl')
                            ->where(array('wxUid'=>$question['wxUserId']))->find();

        $ret['result'] = 'ok';
        $ret['question'] = $question;
        $ret['headimg']=$headImg['headimgurl'];
        //Log::record('--------------=======retret=========='.json_encode($ret),'DEBUG');
        echo json_encode($ret);
    }

    public function check() {
        $txt = I('get.txt');
        import('ORG.Util.Page');// 导入分页类
        $map = array();
        $QuestionDb = D('Question');

        //公告开始时间 小于 或 等于
        $map['appeal'] = array('like','%'.$txt.'%');

        $count = $QuestionDb->where($map)->count();

        $Page = new Page($count);
        // 进行分页数据查询 注意page方法的参数的前面部分是当前的页数使用 $_GET[p]获取
        $nowPage = isset($_GET['p'])?$_GET['p']:1;
        $show       = $Page->show();// 分页显示输出
        $list = $QuestionDb->where($map)->order('sort ASC,date desc')->page($nowPage . ',' . C('web_home_pagenum'))->select();
        $ret['result'] = 'ok';
        $ret['total'] = $count;
        $ret['question'] = $list;
        echo json_encode($ret);
    }

    public function checkBywxuId() {
        $wxuId = I('get.wxuId');
        import('ORG.Util.Page');// 导入分页类
        $map = array();
        $QuestionDb = D('Question');

        //公告开始时间 小于 或 等于
        $map['wxUserId'] = $wxuId ;

        $count = $QuestionDb->where($map)->count();

        $Page = new Page($count);
        // 进行分页数据查询 注意page方法的参数的前面部分是当前的页数使用 $_GET[p]获取
        $nowPage = isset($_GET['p'])?$_GET['p']:1;
        $show       = $Page->show();// 分页显示输出
        $list = $QuestionDb->where($map)->order('sort ASC')->page($nowPage . ',' . C('web_home_pagenum'))->select();
        $ret['result'] = 'ok';
        $ret['total'] = $count;
        $ret['question'] = $list;
        echo json_encode($ret);
    }


    public function checkAnswer() {
        try {
            $wxuId = I('get.wxuId');
            import('ORG.Util.Page');// 导入分页类
            $map = array();
            $QuestionDb = D('Question');

 
            $nowPage = isset($_GET['p'])?$_GET['p']:1;
           
            $list = $QuestionDb->query('
            select * from tp_question 
            where exists(select 1 from tp_answer where tp_answer.qId=tp_question.qId and wxUid='.$wxuId.')
            order by sort ASC,date desc
            limit '.($nowPage-1)*C('web_home_pagenum').', '.$nowPage*C('web_home_pagenum').'
');
            $ret['result'] = 'ok';
            $ret['total'] = $count;
            $ret['question'] = $list;
            echo json_encode($ret);
        }catch(\Exception $e){

            $ret['result'] = 'no';
            $ret['ms'] = $e->getMessage();
            echo json_encode($ret);
        }
    }

    public function upLike(){

        try {
            $QlikelogDb = D('Qlikelog');
            $map=array('qId' => I('qid'),'wxUid' => I('get.wxuId'));
            $likeLog = $QlikelogDb->where($map)->find();
            $addQty=1;
            if ($likeLog != null) {
                if($likeLog['dlike']==1)
                    $addQty=-1;
                $likeLog['dlike'] = 1 - $likeLog['dlike'];
                $QlikelogDb->where($map)->data($likeLog)->save();
                $ret['type'] = '1';
            } else {
                $data = array();
                $data['dlike'] = 1;
                $data['collection'] = 0;
                $data['qId'] = I('qid');
                $data['wxUid'] = I('get.wxuId');
                $QlikelogDb->data($data)->add();
                $ret['type'] = '0';
            }

            $QuestionDb=D('Question');
            $ans=$QuestionDb->where(array('qId'=>I('qid')))->find();
            $ans['likeQty']=$ans['likeQty']+$addQty;
            $QuestionDb->where(array('qId'=>I('qid')))->data($ans)->save();

            $WxUserDb = D('Wxuser');
            $user = $WxUserDb->where(array('wxUid'=>I('get.wxuId')))->find();
            $user['likeQty']+=$addQty;
            $WxUserDb->where(array('wxUid'=>I('get.wxuId')))->data($user)->save();

            $ret['result'] = 'ok';
            echo json_encode($ret);
        }catch(\Exception $e){
            $ret['ms'] = $e->getMessage();
            echo json_encode($ret);
        }
    }

    public function upollection(){

        try {
            $QlikelogDb = D('Qlikelog');
            $map=array('qId' => I('qid'),'wxUid' => I('get.wxuId'));
            $likeLog = $QlikelogDb->where($map)->find();
            $addQty=1;
            if ($likeLog != null) {
                if($likeLog['collection']==1)
                    $addQty=-1;
                $likeLog['collection'] = 1 - $likeLog['collection'];
                $QlikelogDb->where($map)->data($likeLog)->save();
                $ret['type'] = '1';
            } else {
                $data = array();
                $data['dlike'] = 0;
                $data['collection'] = 1;
                $data['qId'] = I('qid');
                $data['wxUid'] = I('get.wxuId');
                $QlikelogDb->data($data)->add();
                $ret['type'] = '0';
            }

            $QuestionDb=D('Question');
            $ans=$QuestionDb->where(array('qId'=>I('qid')))->find();
            $ans['collectionQty']=$ans['collectionQty']+$addQty;
            $QuestionDb->where(array('qId'=>I('qid')))->data($ans)->save();

            $WxUserDb = D('Wxuser');
            $user = $WxUserDb->where(array('wxUid'=>I('get.wxuId')))->find();
            $user['collectionQty']+=$addQty;
            $WxUserDb->where(array('wxUid'=>I('get.wxuId')))->data($user)->save();

            $ret['result'] = 'ok';
            echo json_encode($ret);
        }catch(\Exception $e){
            $ret['ms'] = $e->getMessage();
            echo json_encode($ret);
        }
    }

    public function checkQCById(){
        try{
            $QlikeLogDB = D('Qlikelog');
            $ret = array();
            $ret['result'] = 'ok';
            $ret['iscnn']=$QlikeLogDB
                        ->where(array('wxUid'=>I('get.wxuid'),'collection'=>'1','qId'=>I('get.qid')))
                        ->count()>0?1:0;
            echo json_encode($ret);
        }catch(\Exception $e){
            $ret['ms'] = $e->getMessage();
            echo json_encode($ret);
        }
    }

    public function checkLike() {
        try {
            $wxuId = I('get.wxuId');
            import('ORG.Util.Page');// 导入分页类
            $QuestionDb = D('Question');


            $arr = $QuestionDb->query('
                    select appeal,qId,likeQty,collectionQty 
                    from tp_question a
                    where a.qId in (
                            select a.qId from tp_question a
                            join tp_answer b
                            on a.qId=b.qId
                            join tp_likelog c
                            on c.aId=b.aId
                            where c.wxUid='.$wxuId.' and c.dlike=1
                            UNION
                            select a.qId from tp_question a
                            join tp_qlikelog b
                            on a.qId=b.qId
                            where b.wxUid='.$wxuId.' and b.dlike=1
                    )
            ');

            $list = $arr;
            $ret['result'] = 'ok';
            $ret['question'] = $list;
            echo json_encode($ret);
        }catch(\Exception $e){

            $ret['result'] = 'no';
            $ret['ms'] = $e->getMessage();
            echo json_encode($ret);
        }
    }

    public function checkCollection() {
        try {
            $wxuId = I('get.wxuId');
            import('ORG.Util.Page');// 导入分页类
            $QuestionDb = D('Question');



            $arr = $QuestionDb->query('
                    select appeal,qId,likeQty,collectionQty 
                    from tp_question a
                    where a.qId in (
                            select a.qId from tp_question a
                            join tp_answer b
                            on a.qId=b.qId
                            join tp_likelog c
                            on c.aId=b.aId
                            where c.wxUid='.$wxuId.' and c.collection=1
                            UNION
                            select a.qId from tp_question a
                            join tp_qlikelog b
                            on a.qId=b.qId
                            where b.wxUid='.$wxuId.' and b.collection=1
                    )
            ');

            $list = $arr;
            $ret['result'] = 'ok';
            $ret['question'] = $list;
            echo json_encode($ret);
        }catch(\Exception $e){

            $ret['result'] = 'no';
            $ret['ms'] = $e->getMessage();
            echo json_encode($ret);
        }
    }



    public  function Add(){

        try{
            //throw new \think\Exception('异常消息', 100006);
            $data['content']=I('get.content');
            $data['addr']=I('get.addr');
            $data['birthday']=I('get.birthday');
            $data['appeal']=I('get.appeal');
            $data['isAllergy']=I('get.Allergy');
            $data['isFreckle']=I('get.Freckle');
            $data['ordBrand']=I('get.Brand1');
            $data['newBrand']=I('get.Brand2');
            $data['tip']=I('get.tips');
            $data['pic1']=I('get.pic1');
            $data['pic2']=I('get.pic2');
            $data['pic3']=I('get.pic3');
            $data['formid']=I('get.formId');
            $data['publicImg']=I('get.publicImg');

            $data['date']=date("Y-m-d H:i:s");
            $data['sort']=99;
            $data['wxUserId']=I('get.wxuId');
            $data['answerCount']=0;
            $data['collectionQty']=0;
            $data['likeQty']=0;
            $QuestionDb = D('Question');

            $ret['res'] = $QuestionDb->data($data)->add();


            $ret['result'] = 'ok';
        }catch(\Exception $e){

            $ret['result'] = 'no';
            $ret['ms'] = $e->getMessage();
        }
        echo json_encode($ret);
    }

    public function allTips(){
        $TipsDb = D('Tip');
        $ret = array();
        $ret['result'] = 'ok';
        $ret['arr']=$TipsDb->order('tId ASC')->select();
        echo json_encode($ret);
    }

    public function addrbir(){
        $field='bir,sheng,city,area';
        $wxuId=I('get.wxuId');
        $Wxuser = D('Wxuser');
        $anan=$Wxuser->join('left join tp_member on tp_wxuser.member_id=tp_member.member_id')
            ->field($field)->where(array('wxUid'=>$wxuId))->find();
            $ret['result'] = 'ok';
            $ret['arr']=$anan;
        echo json_encode($ret);

    } 

        // 修改出生日期地址
     public  function rebirthday(){
        try{
             $field="tp_member.bir,sheng,city,area";
          
            $Member = D('Member');
            $wxuId=I('get.wxuId'); 
            $wxuser=D('Wxuser')->where(array('wxUid'=>$wxuId))->find();
            $ret['wx']=$wxuser;
            $ret['member_id']=$wxuser['member_id'];

            $memberData = $Member->where(array('member_id'=>$wxuser['member_id']))->find();
            $memberData['sheng']=I("get.sheng");
            $memberData['city']=I("get.city");
            $memberData['area']=I("get.area");
            $memberData['bir']=I("get.birthday");
            $Member->data($memberData)->save();
            $ret['result'] = 'ok';
            $ret['obj']=$memberData;
            }catch(\Exception $e){

            $ret['result'] = 'no';
            $ret['ms'] = $e->getMessage();
        }
        echo json_encode($ret);
    }

    public  function isfriend(){ 
        $sqid=I("get.sqid");
        $qid=I("get.qid");

        //管理员可见所有图片
        $user = D('Wxuser')->join('join tp_member on tp_wxuser.member_id=tp_member.member_id')
                ->where(array('wxUid'=>$sqid ,'adminUser'=>1))->find();
        if($user)
        {
            $ret['hide']=0;
            echo json_encode($ret);
            exit();
        }


        $field='type';
        $friend=D('Friend')->field($field)->where(array('sqid'=>$sqid,'qid'=>$qid))->order('id desc')->find();
        $ret[friend]=$friend;


        if(empty($friend) || $friend['type']!=1) {  
            $ret[hide]=1; 
        } 
        else if($friend['type']==1){ 
            $ret[hide]=0; 
        }
        echo json_encode($ret);
    }

    public  function addFriend(){ 
        $sqid=I("get.sqid");
        $qid=I("get.qid");
        $field='type';
        $friend=D('Friend')->field($field)->where(array('sqid'=>$sqid,'qid'=>$qid))->find();
        $ret[friend]=$friend;


        if(empty($friend) || $friend['type']==2) {  
            $question = D('Question')->where(array('qId'=>$qid))->find();
            
            $data['sqid']=$sqid; 
            $data['qid']=$qid; 
            $data['bid']=$question['wxUserId']; 
            $data['type']=0; 
            $fid = D('Friend')->data($data)->add();

            $userName = D('Wxuser')->join('join tp_member on tp_wxuser.member_id=tp_member.member_id')
                    ->where(array('wxUid'=>$sqid))->field('nickname')->find();
            $ret['$fid']=$fid;
            $ret['userName']=$userName;
            $ret['question']=$question;
            D('Message')->data(array('message'=>$userName['nickname'].' 向你申请查看问题('.$question['appeal'].')的图片','readed'=>'0','date'=>date("Y-m-d H:i:s"),'wxuid'=>$sqid,'sqid'=>$fid,'qid'=>$qid,'formId'=>I('get.formId'),'doWxuid'=>$question['wxUserId']))->add();

            //send_weapp_msg($touser,$template_id,$page,$form_id,$data,$emphasis_keyword=NULL)
            //申请信息模板
            $qu = D('Wxuser')->join('join tp_member on tp_wxuser.member_id=tp_member.member_id')->where(array('wxUid'=>$question['wxUserId']))->find();

            $val=array( 
                "keyword1"=>array('value'=>$userName['nickname']), 
                "keyword2"=>array('value'=>date("Y-m-d H:i:s")),
                "keyword3"=>array('value'=>' 申请查看问题('.$question['appeal'].')的图片'),
            ); 
            $ret['data']=$val;
            $ret['opid']=$qu['open_id'];
            $ret['tempRes'] = send_weapp_msg($qu['open_id'],'hon9xxypRVFRS-gMcRux94syyVs7w8KxgGQ6TkbLkP0','information/information',$question['formid'],$val,'');

            $ret['result']='申请成功';
        } 
        else if($friend['type']==1){ 
            $ret['result']='已通过';
        }else
            $ret['result']='已申请查看！';
        echo json_encode($ret);
    }
    
    public function getMyMessage(){
        $wxuid=I('get.wxuid');

        import('ORG.Util.Page');// 导入分页类
        $map = array();
        $MessageDb = D('Message');

        //公告开始时间 小于 或 等于
        $map['doWxuid'] = $wxuid;

        $count = $MessageDb->where($map)->count();

        $Page = new Page($count);
        // 进行分页数据查询 注意page方法的参数的前面部分是当前的页数使用 $_GET[p]获取
        $nowPage = isset($_GET['p'])?$_GET['p']:1;
        $show       = $Page->show();// 分页显示输出
        $list = $MessageDb->where($map)->order('readed,date desc ')->page($nowPage . ',' . C('web_home_pagenum'))->select();
        $ret['result'] = 'ok';
        $ret['total'] = $count;
        $ret['Message'] = $list;
        echo json_encode($ret);
    }

    public function passFriend(){
        $sqid=I("get.id");
        $type=I('get.type'); 
        D('Friend')->where(array('id'=>$sqid))->data(array('type'=>$type))->save();
        $ret['result']='ok';
        $ret['type']=$type;


        //信息模板
        $m = D('Message')->where(array('sqid'=>$sqid))->find();
        $userid=$m['wxuid'];
        $formid=$m['formId'];
        $qu = D('Wxuser')->join('join tp_member on tp_wxuser.member_id=tp_member.member_id')->where(array('wxUid'=>$userid))->find();
        
        $f = D('Friend')->where(array('id'=>$sqid))->find();
        $u = D('Wxuser')->join('join tp_member on tp_wxuser.member_id=tp_member.member_id')->where(array('wxUid'=>$f['bid']))->find();
        $val=array( 
            "keyword1"=>array('value'=>$u['nickname']),  
            "keyword2"=>array('value'=>$type==1?'允许查看图片':'拒绝查看图片'),
            "keyword3"=>array('value'=>date("Y-m-d H:i:s")),
        );
        $ret['tempRes'] = send_weapp_msg($qu['open_id'],'pybPvpbD-H_yuwb47anXfFZA1KXa36Wiv30emSQIbg4','wenzhang/wenzhang?id='.$m['qid'],$formid,$val,'');

        D('Question')->where(array('qId'=>$m['qid']))->data(array('formid'=>I('get.formid')))->save();

        echo json_encode($ret);
    }

    public function readMessage(){
        $id=I("get.id");
        D('Message')->where(array('mId'=>$id))->data(array('readed'=>1,'formId'=>I('get.formid')))->save();  
    }
      
    public function upload(){ 
        $uplogo_path = './uploads/image/'; 
        
        if (is_dir($uplogo_path)) {     

            $hash = '';
            $chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
            $max = strlen($chars) - 1;
            mt_srand((double)microtime() * 1000000);
            for($i = 0; $i < 8; $i++)
            {
                $hash .= $chars[mt_rand(0, $max)];
            }

           $img_file_name = time() . $hash . "." . substr(strrchr($_FILES["file"]["name"], '.'), 1); 
            
            if (move_uploaded_file($_FILES["file"]["tmp_name"], $uplogo_path . $img_file_name))
            {  
                $ret['url']='uploads/image/'. $img_file_name;
                $ret['result']='ok';
            }else
                $ret['result']='error'; 
         }
        echo json_encode($ret);
    } 
 
}